<template>
  <div style="border: 1px solid #ddd;">
    <Toolbar
      :editor="editorRef"
      mode="simple"
      :defaultConfig="toolbarConfig"
    />
    <Editor
      :defaultConfig="editorConfig"
      :value="value"
      mode="simple"
      @onCreated="handleCreated"
      @onChange="handleChange"
      style="height: 300px; overflow-y: hidden"
    />
  </div>
</template>

<script setup>
import { onBeforeUnmount, shallowRef,watchEffect } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
// import uploadFile from '@/api/upload'

// 编辑器实例，必须使用 shallowRef ！！！
const editorRef = shallowRef(undefined);
const props = defineProps(['value'])
const emits = defineEmits(["update:value"])
watchEffect(() => {
  if (props.value) {
    editorRef.value?.setHtml(props.value)
  }
});
const editorConfig = {
  placeholder: "请输入内容...",
  // MENU_CONF: {
  //   uploadImage: {
  //     maxFileSize: 3 * 1024 * 1024, // 3M
  //     maxNumberOfFiles: 10,
  //     allowedFileTypes: ['image/*'],
  //     customUpload(file, insertFn) {
  //       uploadFile(file, (_, data) => {
  //         insertFn(data.url, '', data.url)
  //       })
  //     }
  //   }  
  // }
};

// 编辑器创建完成触发
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例
  // editor.disable();
};
const handleChange = () => {
  emits("update:value",editorRef.value?.getHtml())
}
const toolbarConfig = {
  excludeKeys: [
    'insertVideo',
    'insertLink',
    'uploadVideo',
    'uploadImage'
  ]
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>
